public class GenerateMatrix {

    public int[][] generateMatrix(int n) {
        int[][] ans = new int[n][n];
        int a = 0;
        int b = 0;
        int c = n - 1;
        int d= n - 1;
        int start = 1;
        while (a <= c && b <= d) {
            start = process(ans, a++, b++, c-- ,d--, start);
        }
        return ans;
    }

    public int process(int[][] nums, int a, int b, int c, int d, int start) {
        if (a == c && b == d) {
            nums[a][b] = start;
            return ++start;
        } else {
            int x = a;
            int y = b;
            while (y <= d) {
                nums[x][y++] = start++;
            }
            y--;
            x++;
            while (x <= c) {
                nums[x++][y] = start++;
            }
            x--;
            y--;
            while (y >= b) {
                nums[x][y--] = start++;
            }
            y++;
            x--;
            while (x > a) {
                nums[x--][y] = start++;
            }
            return start;
        }
    }
}
